package org.test.unsafe;

import java.lang.reflect.Field;
import sun.misc.Unsafe;

public class SiezofUtil {

	public static Unsafe getUnsafe() {
		try {
			Field f = Unsafe.class.getDeclaredField("theUnsafe");
			f.setAccessible(true);
			return (Unsafe) f.get(null);
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 占用内存字节数 内存的分配是需要对齐的( Memory Alignment,32位CPU存取数据是以4bytes(32bits)为单位)
	 * 总线一次读取的数据必须是完整的，可以有多个数据
	 * 
	 * :在一个类中，数据是按照以下顺序进行存储的。
	 * 
	 * 1.doubles and longs 
	 * 2.ints and floats 
	 * 3.shorts and chars 
	 * 4.booleans and bytes
	 * 5.references 
	 * 
	 * @param object
	 * @return
	 */
	public static long sizeOf(Object object) {
		Unsafe unsafe = getUnsafe();
		return unsafe.getAddress(normalize(unsafe.getInt(object, 4L)) + 12L);
	}

	public static long normalize(int value) {
		if (value >= 0)
			return value;
		return (~0L >>> 32) & value;
	}

	public static void main(String[] args) {
		// 8: 4 (start marker) + 4 (pointer to class)
		System.out.println(sizeOf(new MyStructure0()));

		// 16: 4 (start marker) + 4 (pointer to class) + 4 (int) + 4 stuff bytes
		// to align structure to 64-bit blocks
		System.out.println(sizeOf(new MyStructure1()));

		// 16: 4 (start marker) + 4 (pointer to class) + 2*4
		System.out.println(sizeOf(new MyStructure2()));

		System.out.println(sizeOf(new MyStructure3()));
	}
}
